<template>
  <div class="order-list">
    <div class="page-header">
      <h2>订单管理</h2>
      <button class="btn btn-primary" @click="loadOrders">
        🔄 刷新
      </button>
    </div>

    <!-- 筛选器 -->
    <div class="card filters">
      <div class="filter-group">
        <label>订单状态：</label>
        <select v-model="filters.status" @change="loadOrders">
          <option value="">全部</option>
          <option value="0">待支付</option>
          <option value="1">已支付</option>
          <option value="2">已取消</option>
        </select>
      </div>
    </div>

    <!-- 订单表格 -->
    <div class="card">
      <div v-if="loading" class="loading">加载中...</div>

      <div v-else-if="orders.length === 0" class="empty">
        暂无订单数据
      </div>

      <div v-else>
        <table>
          <thead>
            <tr>
              <th>订单号</th>
              <th>商品名称</th>
              <th>金额</th>
              <th>状态</th>
              <th>发货状态</th>
              <th>创建时间</th>
              <th>支付时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="order in orders" :key="order.id">
              <td>
                <span class="order-no" :title="order.order_no">
                  {{ order.order_no.substring(0, 16) }}...
                </span>
              </td>
              <td>{{ order.product_name }}</td>
              <td class="price">¥{{ order.product_price }}</td>
              <td>
                <span :class="[
                  'status-tag',
                  order.status === 0 ? 'status-pending' :
                    order.status === 1 ? 'status-paid' : 'status-cancelled'
                ]">
                  {{ order.status === 0 ? '待支付' : order.status === 1 ? '已支付' : '已取消' }}
                </span>
              </td>
              <td>
                <span :class="[
                  'status-tag',
                  order.delivery_status === 1 ? 'status-delivered' : 'status-undelivered'
                ]">
                  {{ order.delivery_status === 1 ? '已发货' : '待发货' }}
                </span>
              </td>
              <td>{{ formatDate(order.created_at) }}</td>
              <td>{{ order.pay_time ? formatDate(order.pay_time) : '-' }}</td>
              <td>
                <div class="actions">
                  <button class="btn btn-default btn-sm" @click="showDetail(order)">
                    详情
                  </button>
                  <button v-if="order.status === 0" class="btn btn-primary btn-sm"
                    @click="queryPayment(order.order_no)">
                    查询
                  </button>
                  <button v-if="order.status === 1 && order.delivery_status !== 1" 
                    class="btn btn-success btn-sm"
                    @click="showDeliverModal(order)">
                    发货
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 分页 -->
        <div class="pagination">
          <button class="btn btn-default" :disabled="currentPage <= 1" @click="changePage(currentPage - 1)">
            上一页
          </button>
          <span>第 {{ currentPage }} / {{ totalPages }} 页</span>
          <button class="btn btn-default" :disabled="currentPage >= totalPages" @click="changePage(currentPage + 1)">
            下一页
          </button>
        </div>
      </div>
    </div>

    <!-- 详情弹窗 -->
    <div v-if="showDetailModal" class="modal" @click="closeDetail">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>订单详情</h3>
          <button class="close-btn" @click="closeDetail">✕</button>
        </div>
        <div class="modal-body" v-if="selectedOrder">
          <div class="detail-row">
            <span class="label">订单号：</span>
            <span class="value">{{ selectedOrder.order_no }}</span>
          </div>
          <div class="detail-row">
            <span class="label">商品名称：</span>
            <span class="value">{{ selectedOrder.product_name }}</span>
          </div>
          <div class="detail-row">
            <span class="label">商品价格：</span>
            <span class="value price">¥{{ selectedOrder.product_price }}</span>
          </div>
          <div class="detail-row">
            <span class="label">支付金额：</span>
            <span class="value">{{ selectedOrder.total_fee }}分</span>
          </div>
          <div class="detail-row">
            <span class="label">用户OpenID：</span>
            <span class="value">{{ selectedOrder.openid }}</span>
          </div>
          <div class="detail-row">
            <span class="label">订单状态：</span>
            <span class="value">
              {{ selectedOrder.status === 0 ? '待支付' : selectedOrder.status === 1 ? '已支付' : '已取消' }}
            </span>
          </div>
          <div class="detail-row" v-if="selectedOrder.transaction_id">
            <span class="label">微信交易号：</span>
            <span class="value">{{ selectedOrder.transaction_id }}</span>
          </div>
          <div class="detail-row">
            <span class="label">创建时间：</span>
            <span class="value">{{ selectedOrder.created_at }}</span>
          </div>
          <div class="detail-row" v-if="selectedOrder.pay_time">
            <span class="label">支付时间：</span>
            <span class="value">{{ selectedOrder.pay_time }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 发货弹窗 -->
    <div v-if="showDeliverForm" class="modal" @click="closeDeliverModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>订单发货</h3>
          <button class="close-btn" @click="closeDeliverModal">✕</button>
        </div>
        <div class="modal-body" v-if="currentOrder">
          <div class="order-info-box">
            <div class="info-row">
              <strong>订单号：</strong>{{ currentOrder.order_no }}
            </div>
            <div class="info-row">
              <strong>商品名称：</strong>{{ currentOrder.product_name }}
            </div>
            <div class="info-row">
              <strong>金额：</strong>¥{{ currentOrder.product_price }}
            </div>
          </div>

          <div class="form-group">
            <label>网盘地址 *</label>
            <textarea 
              v-model="deliveryFormData.delivery_content" 
              placeholder="请输入网盘下载地址（如果留空，将使用商品配置的网盘地址）"
              rows="4"
            ></textarea>
            <div class="form-tip">
              💡 提示：如果不填写，系统将自动使用商品配置的网盘地址（如果商品有配置）
            </div>
          </div>

          <div class="form-actions">
            <button class="btn btn-default" @click="closeDeliverModal">取消</button>
            <button class="btn btn-success" @click="submitDeliver">确认发货</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { getOrders, queryPayment as queryPaymentApi, deliverOrder } from '../api/order';

const orders = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const filters = ref({
  status: '',
  openid: ''
});
const showDetailModal = ref(false);
const selectedOrder = ref(null);

// 发货相关状态
const showDeliverForm = ref(false);
const currentOrder = ref(null);
const deliveryFormData = ref({
  delivery_content: ''
});

const totalPages = computed(() => Math.ceil(total.value / pageSize.value));

// 加载订单列表
const loadOrders = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    };

    if (filters.value.status !== '') {
      params.status = filters.value.status;
    }
    if (filters.value.openid) {
      params.openid = filters.value.openid;
    }

    const res = await getOrders(params);
    if (res.success) {
      orders.value = res.data.list;
      total.value = res.data.total;
    } else {
      alert(res.message || '加载失败');
    }
  } catch (error) {
    console.error('加载订单失败:', error);
    alert('网络错误');
  } finally {
    loading.value = false;
  }
};

// 切换页码
const changePage = (page) => {
  currentPage.value = page;
  loadOrders();
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-';
  return dateStr.replace('T', ' ').substring(0, 19);
};

// 显示详情
const showDetail = (order) => {
  selectedOrder.value = order;
  showDetailModal.value = true;
};

// 关闭详情
const closeDetail = () => {
  showDetailModal.value = false;
  selectedOrder.value = null;
};

// 查询支付结果
const queryPayment = async (orderNo) => {
  try {
    const res = await queryPaymentApi(orderNo);
    if (res.success) {
      const { tradeState, tradeStateDesc } = res.data;
      alert(`支付状态：${tradeStateDesc}`);
      if (tradeState === 'SUCCESS') {
        loadOrders();
      }
    } else {
      alert(res.message || '查询失败');
    }
  } catch (error) {
    console.error('查询支付失败:', error);
    alert('网络错误');
  }
};

// 显示发货弹窗
const showDeliverModal = (order) => {
  currentOrder.value = order;
  deliveryFormData.value = {
    delivery_content: '' // 默认为空，后端会自动使用商品网盘地址
  };
  showDeliverForm.value = true;
};

// 关闭发货弹窗
const closeDeliverModal = () => {
  showDeliverForm.value = false;
  currentOrder.value = null;
  deliveryFormData.value = {
    delivery_content: ''
  };
};

// 提交发货
const submitDeliver = async () => {
  if (!currentOrder.value) return;

  try {
    const res = await deliverOrder(currentOrder.value.order_no, deliveryFormData.value);
    if (res.success) {
      alert('发货成功！');
      closeDeliverModal();
      loadOrders();
    } else {
      alert(res.message || '发货失败');
    }
  } catch (error) {
    console.error('发货失败:', error);
    alert('网络错误: ' + (error.message || '未知错误'));
  }
};

onMounted(() => {
  loadOrders();
});
</script>

<style scoped>
.order-list {
  max-width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.filters {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.actions {
  display: flex;
  gap: 8px;
}

.btn-sm {
  padding: 4px 12px;
  font-size: 12px;
}

.order-no,
.openid {
  font-family: monospace;
  font-size: 12px;
  color: #666;
  cursor: help;
}

.price {
  color: #ff4d4f;
  font-weight: 600;
}

/* 发货状态标签 */
.status-delivered {
  background: #f0f9ff;
  color: #1890ff;
}

.status-undelivered {
  background: #fff7e6;
  color: #fa8c16;
}

/* 发货表单样式 */
.order-info-box {
  background: #f5f5f5;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.order-info-box .info-row {
  margin-bottom: 8px;
  font-size: 14px;
}

.order-info-box .info-row:last-child {
  margin-bottom: 0;
}

.form-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #1890ff;
  line-height: 1.6;
}

.btn-success {
  background: #52c41a;
  color: white;
  border: none;
}

.btn-success:hover {
  background: #73d13d;
}

/* 弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e5e5e5;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #333;
}

.modal-body {
  padding: 20px;
}

.detail-row {
  display: flex;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.detail-row:last-child {
  border-bottom: none;
}

.detail-row .label {
  width: 120px;
  color: #666;
  font-size: 14px;
  flex-shrink: 0;
}

.detail-row .value {
  flex: 1;
  color: #333;
  font-size: 14px;
  word-break: break-all;
}
</style>
